<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <link rel="shortcut icon" href="pingpong.png">
    <link rel="stylesheet" type="text/css" href="pingpong.css">
    <title>Async Servlet</title>
</head>
<body>

<div id="field">
    <div id="player2" class="player"></div>
    <div id="player1" class="player"></div>
    <div id="ball"></div>
</div>
<div id="scoreBoard">
    0 - 0
</div>

<script type="text/javascript" src="jQuery/jquery-2.0.3.js"></script>
<script type="text/javascript" src="jQuery/jquery.atmosphere.js"></script>

<script type="text/javascript">
    (function() {

        var $field = $('#field');
        var $ball = $('#ball');
        var $player1 = $('#player1');
        var $player2 = $('#player2');
        var $scoreBoard = $('#scoreBoard');
        var playerPosition = 300;

        function callback(player1Left, player2Left, ballTop, ballLeft, score1, score2) {
            $ball.css('left', ballLeft);
            $ball.css('top', ballTop);
            $player1.css('left', player1Left);
            $player2.css('left', player2Left);
            $scoreBoard.text(score1 + ' - ' + score2);
        };

        $field.mousemove(function(event) {
            playerPosition = event.pageX
        });

        var socket = $.atmosphere;

        // We are now ready to cut the request
        var request = {url: 'atmosphere/pingpong/websocket',
            contentType : "application/json",
            transport : 'websocket'};

        request.onMessage = function (response) {
            var message = response.responseBody;
            var params = message.split(',');
            callback(parseInt(params[0]), parseInt(params[1]), parseInt(params[2])
                    , parseInt(params[3]), parseInt(params[4]), parseInt(params[5]))
        }

        request.onClose = function(response) {
            console.log('Closed');
        };

        request.onError = function(response) {
            console.log('Error');
        };

        var subSocket = socket.subscribe(request);

        function go() {
            subSocket.push(playerPosition + '');
        }
        setInterval(go, 25);
    })();
</script>

</body>
</html>